package org.example.ui;

import org.example.dao.SoftDao;
import org.example.dao.impl.SoftDAOImpl;
import org.example.entity.Soft;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class SoftManagementPanel extends JPanel {
    private JTable table;
    private DefaultTableModel tableModel;
    private SoftDao softDAO;

    public SoftManagementPanel() {
        softDAO = new SoftDAOImpl();
        setLayout(new BorderLayout());

        // 创建表格
        String[] columnNames = {"ID", "项目名称", "部门ID", "用户ID", "日期"};
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton refreshButton = new JButton("刷新");
        JButton addButton = new JButton("添加");
        JButton editButton = new JButton("编辑");
        JButton deleteButton = new JButton("删除");

        buttonPanel.add(refreshButton);
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);

        add(buttonPanel, BorderLayout.SOUTH);

        // 添加按钮事件
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable();
            }
        });

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddDialog();
            }
        });

        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow >= 0) {
                    int id = (int) table.getValueAt(selectedRow, 0);
                    showEditDialog(id);
                } else {
                    JOptionPane.showMessageDialog(SoftManagementPanel.this,
                            "请选择要编辑的项目", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                if (selectedRow >= 0) {
                    int id = (int) table.getValueAt(selectedRow, 0);
                    int confirm = JOptionPane.showConfirmDialog(
                            SoftManagementPanel.this,
                            "确定要删除这个项目吗?",
                            "确认删除",
                            JOptionPane.YES_NO_OPTION);

                    if (confirm == JOptionPane.YES_OPTION) {
                        softDAO.deleteSoft(id);
                        refreshTable();
                    }
                } else {
                    JOptionPane.showMessageDialog(SoftManagementPanel.this,
                            "请选择要删除的项目", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });

        // 初始化表格数据
        refreshTable();
    }

    private void refreshTable() {
        tableModel.setRowCount(0);
        List<Soft> softs = softDAO.getAllSofts();

        for (Soft soft : softs) {
            tableModel.addRow(new Object[]{
                    soft.getSoft_id(),
                    soft.getSoft_name(),
                    soft.getDept_id(),
                    soft.getUse_id(),
                    soft.getHire_date()
            });
        }
    }

    private void showAddDialog() {
        JTextField nameField = new JTextField();
        JTextField deptIdField = new JTextField();
        JTextField useIdField = new JTextField();
        JTextField dateField = new JTextField();

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("项目名称:"));
        panel.add(nameField);
        panel.add(new JLabel("部门ID:"));
        panel.add(deptIdField);
        panel.add(new JLabel("用户ID:"));
        panel.add(useIdField);
        panel.add(new JLabel("日期 (yyyy-MM-dd):"));
        panel.add(dateField);

        int result = JOptionPane.showConfirmDialog(
                this, panel, "添加项目", JOptionPane.OK_CANCEL_OPTION);

        if (result == JOptionPane.OK_OPTION) {
            try {
                String name = nameField.getText();
                int deptId = Integer.parseInt(deptIdField.getText());
                int useId = Integer.parseInt(useIdField.getText());
                Date hireDate = parseDate(dateField.getText());

                Soft soft = new Soft();
                soft.setSoft_name(name);
                soft.setDept_id(deptId);
                soft.setUse_id(useId);
                soft.setHire_date(hireDate);

                softDAO.addSoft(soft);
                refreshTable();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(
                        this, "输入有误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void showEditDialog(int id) {
        Soft soft = softDAO.getSoftById(id);
        if (soft == null) {
            JOptionPane.showMessageDialog(this, "项目不存在", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JTextField nameField = new JTextField(soft.getSoft_name());
        JTextField deptIdField = new JTextField(String.valueOf(soft.getDept_id()));
        JTextField useIdField = new JTextField(String.valueOf(soft.getUse_id()));
        JTextField dateField = new JTextField(
                soft.getHire_date() != null ? soft.getHire_date().toString() : "");

        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(new JLabel("项目名称:"));
        panel.add(nameField);
        panel.add(new JLabel("部门ID:"));
        panel.add(deptIdField);
        panel.add(new JLabel("用户ID:"));
        panel.add(useIdField);
        panel.add(new JLabel("日期 (yyyy-MM-dd):"));
        panel.add(dateField);

        int result = JOptionPane.showConfirmDialog(
                this, panel, "编辑项目", JOptionPane.OK_CANCEL_OPTION);

        if (result == JOptionPane.OK_OPTION) {
            try {
                String name = nameField.getText();
                int deptId = Integer.parseInt(deptIdField.getText());
                int useId = Integer.parseInt(useIdField.getText());
                Date hireDate = parseDate(dateField.getText());

                soft.setSoft_name(name);
                soft.setDept_id(deptId);
                soft.setUse_id(useId);
                soft.setHire_date(hireDate);

                softDAO.updateSoft(soft);
                refreshTable();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(
                        this, "输入有误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private Date parseDate(String dateStr) throws ParseException {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date utilDate = sdf.parse(dateStr);
        return new Date(utilDate.getTime());
    }
}